package com.sl.proxy.core.coder;

import cn.hutool.core.collection.CollUtil;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.*;
import lombok.SneakyThrows;
import org.apache.commons.compress.utils.Lists;

import java.util.List;

public class CustomHttpRequestDecoder extends HttpRequestDecoder {


    @SneakyThrows
    public DefaultFullHttpRequest decode(ByteBuf buffer) {
        List<Object> objects = Lists.newArrayList();

        readAll(objects, buffer);
        if (CollUtil.isEmpty(objects)) {
            return null;
        }
        //再读一次
//        super.decode(null, buffer, objects);

        HttpRequest message = findMessage(objects);
        LastHttpContent content = findContent(objects);

        //HttpVersion httpVersion, HttpMethod method, String uri, ByteBuf content, HttpHeaders headers, HttpHeaders trailingHeader
        DefaultFullHttpRequest httpObjectAggregator = new DefaultFullHttpRequest(
                message.protocolVersion(),
                message.method(),
                message.uri(),
                content.content(),
                message.headers(),
                content.trailingHeaders()
        );

        return httpObjectAggregator;
    }

    public LastHttpContent findContent(List<Object> objects) {
        LastHttpContent httpRequest = null;
        for (Object object : objects) {
            if (object instanceof LastHttpContent hr) {
                httpRequest = hr;
                break;
            }
        }
        return httpRequest;
    }

    public HttpRequest findMessage(List<Object> objects) {
        HttpRequest httpRequest = null;
        for (Object object : objects) {
            if (object instanceof HttpRequest hr) {
                httpRequest = hr;
                break;
            }
        }
        return httpRequest;
    }

    @SneakyThrows
    public void readAll(List<Object> objects, ByteBuf buffer) {

        super.decode(null, buffer, objects);
        if (CollUtil.isEmpty(objects)) {
            return;
        }
        Object last = CollUtil.getLast(objects);
        if (last instanceof LastHttpContent) {
            return;
        }
        readAll(objects, buffer);
    }
}
